using IQIGame.Onigao.Framework;
using System.Collections.Generic;

namespace IQIGame.Onigao.Game
{
    public class CFSMCondition : IReusableClass
    {
        public uint MaxStore => 50;
        public int id { get; private set; }
        public int nextStateId { get; private set; }

        private List<BaseConditionFunc> logicFuncs = new List<BaseConditionFunc>();

        public void Init(ConfigurableFSM fsm, string fsmName, CFSMConditionCfg cfgCondition)
        {
            this.id = cfgCondition.id;
            this.nextStateId = cfgCondition.nextStateId;
            foreach (CFSMConditionPartCfg cfgPart in cfgCondition.parts)
            {
                BaseConditionFunc func = CreateConditionFunc(fsm, fsmName, cfgPart);
                logicFuncs.Add(func);
            }
        }

        private BaseConditionFunc CreateConditionFunc(ConfigurableFSM fsm, string fsmName, CFSMConditionPartCfg cfgPart)
        {
            BaseConditionFunc condFunc;
            if (cfgPart.isPublic)
            {
                condFunc = CFStateMachineManager.Instance.blackboard.CreateCommonConditionFunc(cfgPart.funcName);
            }
            else
            {
                condFunc = CFStateMachineManager.Instance.blackboard.CreateConditionFunc(fsmName, cfgPart.funcName);
            }
            condFunc.Init(fsm, cfgPart);
            return condFunc;
        }


        public bool Check()
        {
            bool isOK = true;
            for (int i = 0; i < logicFuncs.Count; i++)
            {
                BaseConditionFunc func = logicFuncs[i];
                switch (func.prevLogicOperation)
                {
                    case LogicOperation.None:
                        isOK = func.Check();
                        break;
                    case LogicOperation.And:
                        isOK = isOK && func.Check();
                        break;
                    case LogicOperation.Or:
                        isOK = isOK || func.Check();
                        break;
                }
            }
            return isOK;
        }

        public void OnReset()
        {
            id = 0;
            foreach (var func in logicFuncs)
            {
                ClassPool.PutAutoType(func);
            }
            logicFuncs.Clear();
            nextStateId = 0;
        }
    }
}
